<template>
    <view class="page" :style="{'--color': color, '--total-height': totalHeight + 'px'}">
		<status-bar title='我的订单' :back="back"></status-bar>
		<backTop v-if='toTop'></backTop>
		<view class="topArea bgf8">
			<view class="nav thmeBg d-flex" v-if="orderType.length">
				<view class="flex-1 flexac size28 white" :class="{'bgwhite bor_radius_30 thmeColor': type == item.type}" @click="navClick(item.type)" 
					v-for="(item,index) in orderType" :key="index">{{ item.title }}</view>
			</view>
			<scroll-view class="tabs" scroll-x :scroll-into-view="tabIndex < 4 ? 'tab0' : 'tab' + tabIndex" scroll-with-animation>
				<view class="d-inline-block size28 color_11" :class="{'size30 thmeColor': tabIndex == index, 'unread': item.show == 1 && item.num > 0}" :data-num="item.num"
					:id="'tab' + index" @click="tabClick(index, item.state)" v-for="(item,index) in orderTitle" :key="index">{{ item.name }}</view>
			</scroll-view>
		</view>
		<view :style="{'padding-top': orderType.length ? '164rpx' : '80rpx'}">
			<view class="order_item" v-for="(item,index) in list" :key="index">
				<view class="d-flex m-bot24">
					<view class="flex-1 size32">{{ item.name || startUp.title }}</view>
					<view class="size28 color_66">
						<block v-if="item.state == 0">待支付</block>
						<block v-if="item.state == 1">{{ item.type == 2 && item.group_state == 0 ? '待成团' : ( item.delivery == 1 ? '待发货' : '备货中' ) }}</block>
						<block v-if="item.state == 2 || item.state == 3">{{ item.delivery == 2 ? '待取货' : '待收货' }}</block>
						<block v-if="item.state == 4">待评价</block>
						<block v-if="item.state == 5">已评价</block>
						<block v-if="item.state == 6">退款中</block>
						<block v-if="item.state == 96">退款成功</block>
						<block v-if="item.state == 97">已失效</block>
						<block v-if="item.state == 98">已取消</block>
					</view>
				</view>
				<view class="alert bor_radius_4 d-flex j-sb a-center m-bot24" v-if="item.type == 2 && item.group_state == 0 && item.groupTime > 0">
					<view class="size26 white">{{ item.personalNum > 0 ? `还差${item.personalNum}人成团` : '已满员' }}</view>
					<count-down :time="item.groupTime" startTxt="剩余" endTxt="拼团" txtColor="#fff" />
				</view>
				<!-- 多商品 -->
				<view class="p-re" @click="toDetail(item.order_id, item.table_code_id)" v-if="item.goodsData">
					<scroll-view class="scroll-row" scroll-x>
						<view class="scroll-item d-inline-block m-right20 p-re" v-for="(subItem,subIndex) in item.goodsData" :key="subIndex">
							<image class="img bor_radius_10 m-bot10" :src="subItem.goods_img ? $imgUrls(subItem.goods_img) : staticUrl + '/images/imageLoading.png'" mode="aspectFill"></image>
							<view class="name text-center">{{ subItem.goods_name }}</view>
							<view class="badge white p-ab" v-if="subItem.goods_num > 1">x {{ subItem.goods_num }}</view>
						</view>
					</scroll-view>
					<view class="total d-flex f-column j-centert a-end p-ab">
						<view class="m-bot10">
							<text class="size28">￥</text>
							<text class="size36">{{ getPrice(item).frontPrice }}</text>
							<text class="size28" v-if="getPrice(item).backPrice">.{{ getPrice(item).backPrice }}</text>
						</view>
						<view class="color_66">共 {{ parseInt(item.num) }} 件</view>
					</view>
				</view>
				<view class="size28 color_66 m-top24" v-if="item.goodsData">下单：{{ $common.timeFormat(item.add_time, 'Y-M-D h:m') }}</view>
				<!-- 单商品 -->
				<view class="d-flex a-center" @click="toDetail(item.order_id, item.table_code_id)" v-else>
					<image class="img bor_radius_10" :src="item.goods_img ? $imgUrls(item.goods_img) : staticUrl + '/images/imageLoading.png'" mode="aspectFill"></image>
					<view class="flex-1 m-left20">
						<view class="ellipsis">
							<text class="speTag" v-if="item.type == 1">特价</text>
							<text class="speTag" v-if="item.type == 2">团购</text>
							<text class="size28">{{ item.goods_name }}</text>
						</view>
						<view class="size28 color_66 m-top10" v-if="item.specs_bind_text">{{ item.specs_bind_text }}</view>
						<view class="size28 color_66 m-top10">下单：{{ $common.timeFormat(item.add_time, 'Y-M-D h:m') }}</view>
					</view>
					<view class="text-right m-left20">
						<view class="m-bot10">
							<text class="size28">￥</text>
							<text class="size36">{{ getPrice(item).frontPrice }}</text>
							<text class="size28" v-if="getPrice(item).backPrice">.{{ getPrice(item).backPrice }}</text>
						</view>
						<view class="color_66">共 {{ item.goods_num }} 件</view>
					</view>
				</view>
				<view class="d-flex j-end m-top24">
					<view class="btn plain" v-if="(item.state == 0 || (item.pay_type == 2 && item.state == 1)) && item.table_code_id == 0" @click="show_model(item, index, 0)">取消订单</view>
					<view class="btn plain" v-if="item.refuse_state == 1 && item.pay_type == 2 && ['2','3','5'].includes(item.state)" @click="show_model(item, index, 1)">退货退款</view>
					<view class="btn plain" v-if="item.refuse_state == 1 && item.pay_type != 2 && item.state > 0 && item.state < 6" @click="show_model(item, index, 1)">退货退款</view>
					<view class="btn plain" v-if="item.delivery == 1 && (item.state == 2 || item.state == 3)" @click="toUrl('/orderPage/order/logistics?order_id=' + item.order_id)">查看物流</view>
					<view class="btn plain" v-if="['4','5','96','97','98'].includes(item.state)" @click="show_model(item, index, 2)">删除订单</view>
					<view class="btn" v-if="item.state == 0" @click="payNow(item.payID)">去支付</view>
					<view class="btn" v-if="item.delivery == 1 && (item.state == 2 || item.state == 3)" @click="show_model(item, index, 3)">确认收货</view>
					<view class="btn" v-if="item.delivery == 2 && (item.state == 2 || item.state == 3)" @click="getCode(item.order_id)">提货码</view>
					<block v-if="bid != 'cymr1gp9VHne4HgQSxgUOQ=='">
						<view class="btn" v-if="item.rebuy_button == 1 && (item.state == 96 || item.state == 98)" @click="buyAgain(item)">再次购买</view>
					</block>
					<view class="btn" v-if="item.state == 4" @click="toUrl('/commentPage/comment/commentGoods?oid=' + item.order_id)">立即评价</view>
					<!-- #ifdef MP-WEIXIN -->
					<view v-if="item.state == 1 && item.type == 2 && item.group_id != 0">
						<button class="btn" open-type="share" :data-item="item">去分享</button>
					</view>
					<!-- #endif -->
				</view>
			</view>
			
			<view v-if="noMore && page > 1" class="DiLine">没有更多了</view>
			<empty v-if="noData" cat='3' msg='您还没有相关的订单'></empty>
		</view>
		
		<!-- 提货码 -->
		<view class="mask flexac f-column" @click="codeInfo = ''" v-if="codeInfo">
			<view class="code_pop text-center" :style="{backgroundImage: 'url(' + staticUrl + '/images/pickup_code_pop_bg.png)'}" @click.stop>
				<view class="size32 p-top80 p-bot70">请向店员出示取货二维码</view>
				<image :src="$imgUrls(codeInfo.url)" mode="aspectFit" class="code_img"></image>
				<view class="size32 m-top40">{{ codeInfo.code }}</view>
			</view>
			<text class="iconfont icon-guanbi size60" @click="codeInfo = ''"></text>
		</view>
		
		<showModel v-if="showModal" type="99" :title="title" :msg="msg" :btn1="btn1" :btn2="btn2" @certain="certain" @cancelFunc="showModal = false"></showModel>
		
		<tabBar :tab="13" v-if="back == 0"></tabBar>
    </view>
</template>

<script>
	import { mapState } from 'vuex'
    export default {
		data() {
			return {
				staticUrl: this.staticUrl,
				back: 1,
				toTop: false,
				orderType: [],
				type: '',
				orderTitle: [],
				tabIndex: 0,
				state: 666,
				list: [],
				page: 1,
				noMore: false,
				noData: false,
				codeInfo: '', // 提货码
				pageData: '', // 当前操作订单对象
				orderIndex: 0,
				showModal: false,
				modelType: '',
				title: '',
				msg: '',
				btn1: '',
				btn2: ''
			}
		},
        computed: {
			...mapState(['color', 'totalHeight', 'startUp', 'bid', 'vid'])
		},
		onLoad(e) {
			if(e.type) this.type = e.type
			if(e.status) this.state = e.status
			if(e.back) this.back = e.back
			this.getList(true)
			
			// #ifdef MP
			uni.hideShareMenu()
			// #endif
		},
		methods: {
			getList(init) {
				this.$showLoading('')
				this.noData = false
				this.noMore = false
				this.$http.post({
					url: '/zzj_singleSaleApi/orderList',
					data: {
						type: this.type,
						state: this.state,
						page: this.page,
						pagecount: 10
					}
				}).then(res => {
					this.$hideLoading()
					uni.stopPullDownRefresh()
					if(res.errcode != 100) return this.$Toast(res.msg)
					let result = res.data || []
					this.list = this.page == 1 ? result : this.list.concat(result)
					if(result.length < 10) this.noMore = true
					if(!this.list.length) this.noData = true
					
					this.orderType = res.resOrderType || []
					this.orderTitle = res.resOrderCount || []
					if(!this.type && this.orderType.length) this.type = this.orderType[0].type
					if(!init || this.state == 666) return
					let index = this.orderTitle.findIndex(item => item.state == this.state)
					if(index > -1) this.tabIndex = index
				})
			},
			navClick(type) {
				this.type = type
				this.tabIndex = 0
				this.state = 666
				this.page = 1
				this.getList()
			},
			tabClick(index, state) {
				this.tabIndex = index
				this.state = state
				this.page = 1
				this.getList()
			},
			getCode(order_id) {
				this.$http.post({
					url: '/zzj_singleSaleApi/get_qrcode',
					data: {
						order_id
					}
				}).then(res => {
					if(res.url) this.codeInfo = res
				})
			},
			async show_model(item, index, type) {
				this.pageData = item
				this.orderIndex = index
				this.modelType = type
				if(type == 0) {
					this.title = '是否确定取消订单？'
					this.msg = '可在已取消列表找到'
					this.btn1 = '我再想想'
					this.btn2 = '确定'
					this.showModal = true
				}
				if(type == 1) {
					this.title = '是否确定退货退款？'
					this.msg = '退货退款成功后将不可撤回'
					this.btn1 = '我再想想'
					this.btn2 = '退意已决'
					this.showModal = true
				}
				if(type == 2) {
					this.title = '是否确定删除订单？'
					this.msg = '删除后将不可恢复！'
					this.btn1 = '取消'
					this.btn2 = '确定'
					this.showModal = true
				}
				if(type == 3) {
					this.title = '是否确定已收到宝贝？'
					this.msg = '确认收货后将不可撤销操作'
					this.btn1 = '取消'
					this.btn2 = '确认收货'
					if(item.payment == 0) return this.showModal = true
					const Result = await this.$pop.getTxConfirm(item.order_id)
					if(Result != 2) return this.showModal = true
					if(wx.openBusinessView) {
						wx.openBusinessView({
							businessType: 'weappOrderConfirm',
							extraData: {
								transaction_id: item.transaction_id
							},
							success: e => {
								if(e.extraData.status == 'success') {
									this.receipt()
								}
							},
							complete(res) {
								console.log('确认收货接口', res)
							}
						})
					} else {
						this.$Toast('请先升级到最新的微信版本')
					}
				}
			},
			certain() {
				if(this.modelType == 0) { // 取消订单
					this.$http.post({
						url: '/zzj_singleSaleApi/cancelOrder',
						data: {
							order_id: this.pageData.order_id
						}
					}).then(res => {
						this.cancel(res)
					})
				}
				if(this.modelType == 1) { // 退货退款
					this.$http.post({
						url: '/zzj_singleSaleApi/refund',
						data: {
							order_id: this.pageData.order_id
						}
					}).then(res => {
						this.cancel(res)
					})
				}
				if(this.modelType == 2) { // 删除订单
					this.$http.post({
						url: '/zzj_singleSaleApi/delOrder',
						data: {
							order_id: this.pageData.order_id
						}
					}).then(res => {
						this.cancel(res)
					})
				}
				if(this.modelType == 3) { // 确认收货
					this.receipt()
				}
			},
			receipt() {
				this.$http.post({
					url: '/zzj_singleSaleApi/receivingGoods',
					data: {
						order_id: this.pageData.order_id
					}
				}).then(res => {
					this.cancel(res)
					if(res.status) this.toUrl('/orderPage/order/receiptSuccess?oid=' + this.pageData.order_id)
				})
			},
			cancel(res) {
				this.$Toast(res.msg)
				this.showModal = false
				this.page = 1
				this.getList()
			},
			payNow(payID) {
				// #ifdef H5
				window.location.href = 'https://sra.mogoie.com/index.php/accountPay/weChatCashierPage?orderStr=' + payID
				// #endif
				// #ifndef H5
				this.toUrl('/moneyPage/capital/checkstand?payid=' + payID)
				// #endif	
			},
			buyAgain(item) {
				if(item.goodsData) { // 多商品
					let arr = []
					item.goodsData.forEach((subItem,subIndex) => {
						this.$http.post({
							url: '/zzj_singleSaleApi/joinCart',
							data: {
								goods_id: subItem.goods_id,
								specs_bind_id: subItem.specs_bind_id,
								specs_bind_text: subItem.specs_bind_text,
								num: parseInt(subItem.goods_num)
							}
						}).then(res => {
							if(res.errcode != 100) return this.$Toast(res.msg)
							arr.push(res.car_id)
							if(subIndex == item.goodsData.length - 1) {
								uni.setStorageSync('buyway', '')
								this.toUrl('/orderPage/order/createOrders?car_id=' + arr.join())
							}
						})
					})
				} else { // null
					let param = '?goods_id=' + item.goods_id + '&goods_num=' + item.goods_num
					if(item.specs_bind_id) param = param + '&specs_bind_id=' + item.specs_bind_id + '&specs_bind_text=' + item.specs_bind_text
					this.toUrl('/orderPage/order/createOrders' + param)
				}
			},
			toDetail(order_id, tid) {
				if(tid == 0) return this.toUrl('/orderPage/order/orderDetail?order_id=' + order_id)
				this.toUrl('/otherPage/custom/viewOrder?order_id=' + order_id + '&tid=' + tid)
			},
			getPrice(item) {
				let price = (parseFloat(item.payment) + parseFloat(item.used_balance)).toString()
				return {
					frontPrice: price.split('.')[0],
					backPrice: price.split('.')[1]
				}
			}
		},
		onReachBottom() {
			if(this.noMore) return
			this.page ++
			this.getList()
		},
		onPullDownRefresh() {
			this.page = 1
			this.getList()
		},
		onShareAppMessage(res) {
			// button添加的data-*属性会传到res.target.dataset
			if(res.from == 'button') {
				let { goods_name, goods_id, act_id, group_id, goods_img } = res.target.dataset.item
				return {
					title: goods_name,
					path: '/pages/index/index?share_v_id=' + this.vid + '&pageType=3&gid=' + goods_id + '&aid=' + act_id + '&group_id=' + group_id,
					imageUrl: this.$imgUrls(goods_img)
				}
			}
		},
		onPageScroll(e) {
			if(e.scrollTop > 200) {
				this.toTop = true
			} else {
				this.toTop = false
			}
		}
    }
</script>

<style lang="scss" scoped>
	.page {
		background-color: #f8f8f8;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		/deep/ .fixed1 {
			background: #f8f8f8 !important;
		}
	}
	.topArea {
		width: 100%;
		position: fixed;
		top: var(--total-height);
		left: 0;
		z-index: 99;
		.nav {
			width: 710rpx;
			height: 64rpx;
			border-radius: 32rpx;
			padding: 4rpx;
			margin: 10rpx auto;
		}
		.tabs {
			white-space: nowrap;
			height: 80rpx;
			line-height: 80rpx;
			view {
				padding: 0 30rpx;
			}
			.unread::after {
				left: 72%;
				top: 2rpx;
				text-align: center;
			}
		}
	}
	.order_item {
		width: 710rpx;
		background: #fff;
		border-radius: 10rpx;
		padding: 24rpx 20rpx;
		margin: 0 auto 24rpx;
		.alert {
			height: 48rpx;
			background: #ffbb7f;
			padding: 0 30rpx;
		}
		.scroll-item {
			width: 160rpx;
			&:last-child {
				margin-right: 140rpx;
			}
		}
		.img {
			width: 160rpx;
			height: 160rpx;
		}
		.name {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		.badge {
			background: rgba(0, 0, 0, .5);
			border-radius: 0 10rpx 0 10rpx;
			padding: 0 10rpx;
			left: 0;
			top: 160rpx;
			transform: translateY(-100%);
		}
		.total {
			min-width: 160rpx;
			height: 210rpx;
			background: linear-gradient(to left, #fff, rgba(255, 255, 255, .9));
			right: 0;
			top: 0;
		}
		.btn {
			width: 172rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
			text-align: center;
			box-sizing: border-box;
			margin-left: 20rpx;
			font-size: 28rpx;
			border: 2rpx solid var(--color);
			color: var(--color);
			&.plain {
				border: 2rpx solid #989898;
				color: #1b1b1b;
			}
		}
	}
	.code_pop {
		width: 600rpx;
		height: 800rpx;
		background-size: 100% 100%;
		.code_img {
			width: 440rpx;
			height: 440rpx;
		}
	}
</style>